<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use \app\back\model\WeixinQueue;
use \app\common\libs\WeixinHelper;


class WeixinTplMessage extends Command
{
   protected function configure()
    {
        $this->setName('weixin_message_queue')->setDescription('Regularly execute WeChat message queues');
    }

    protected function execute(Input $input, Output $output)
    {
        
    	$queue_model = new WeixinQueue;
    	$list = $queue_model->where('state','in', ['0', '2'])->where('times', '<', '3')->select();

    	if(empty($list)){
    		$output->writeln("no message to send");
    		die;
    	}

    	$success_ids = $ids = [];
    	foreach ($list as $key => $value) {
    		$ids[] = $value->id;
    	}

    	$queue_model->where('id','in', $ids)->update(['state'=>'1']);

    	foreach ($list as $key => $value) {
    		switch ($value->message_type) {
    			// 微信模拟消息
    			case 'weixin_tpl':
    				$result = WeixinHelper::sendTplMessage($value->content, token());

    				if($result['errmsg'] !== 'ok') {
    					$value->reason = $result['errmsg'];
    					$value->reason = ($value->reason+1);
    					$value->state = 2;
    					$value->save();
    				} else {
    					$success_ids[] = $value->id;
    				}
    				break;
    			
                case 'weixin_kefu':
                    WeixinHelper::kfMessage(json_decode($value->content),token());
                    $success_ids[] = $value->id;
                    break;
    			default:
    				# code...
    				break;
    		}
    	}

    	!empty($success_ids) && $queue_model->where('id', 'in', $success_ids)->delete();

        $output->writeln("complete");
    }
}
